<template>
  <view class="click" @click="sendCodeProcessor">
    <slot :remainder="remainder" :isWait="isWait"></slot>
  </view>
</template>

<script setup lang="ts">
import { nextTick } from 'vue'
import { ref, watch } from 'vue'
const props = defineProps({
  sendCode: {
    type: Function,
    default: () => new Promise((resolve) => resolve(true))
  },
  interval: {
    type: Number,
    default: 60
  }
})
// 是否在进行倒计时
const isWait = ref(false)
// 剩余倒计时间
const remainder = ref<number>(0)
let timer = ref<number | null>()
// 关闭倒计时
function closeCountdown() {
  if (timer.value == null) return
  clearInterval(timer.value!)
  timer.value = null
  remainder.value = 0
  nextTick(() => {
    isWait.value = false
  })
}

// 启动倒计时（会根据传入的异步函数决定是否要取消）
async function sendCodeProcessor() {
  if (remainder.value > 0) return
  remainder.value = props.interval
  // 开启倒计时
  isWait.value = true
  timer.value = setInterval(() => {
    if (remainder.value-- < 1) closeCountdown()
  }, 1000)
  // 当异常时，取消倒计时
  await props.sendCode().catch(() => closeCountdown())
}
</script>

<style scoped></style>
